' Normal testing:
'c:\wiki_import\input\ /scan /imgpath c:\wiki_import\images /logpath c:\wiki_import\logs /artpath c:\wiki_import\articles /arturl http://wikirs/meridianbeta/index.php?title=%title% /dbserver wikirs /db wikidb /dblogin root /dbpassword mysql /tableprefix wikibeta_ /linktosource /linkpublictext %filename% /linkprivatetext [[file:\\joekessler2\shared_folder\%filename%]]

Imports System
Imports System.Data
Imports System.Net
Imports System.IO
Imports MySql.Data.MySqlClient

Module Main
    Dim DBServer As String
    Dim DB As String
    Dim DBLogin As String
    Dim DBPassword As String
    Dim ScrapeFromSite As Boolean
    Dim SiteLogin As String = ""
    Dim SitePassword As String = ""
    Dim FullyQualifiedFilename As String

    Function Main(ByVal ArgList As String()) As Integer
        Dim ShowHelp As Boolean
        If ArgList.Length = 0 Then
            ShowHelp = True
        ElseIf ArgList(0) = "/?" Then
            ShowHelp = True
        Else
            ShowHelp = False
        End If

        Dim imp As Impersonator = Nothing
        Dim connStr As String
        Dim conn As MySqlConnection

        Try
            ' Construct our importer instance.
            Dim Arg As String
            Dim NextParm As String


            DBServer = Nothing
            DB = Nothing
            DBLogin = Nothing
            DBPassword = Nothing
            SiteLogin = Nothing
            SitePassword = Nothing

            ' Read in parms that absolutely must go first! 
            Dim defaultsFile As String = "DefaultSettings.ini"
            NextParm = Nothing

            For Each Arg In ArgList
                If NextParm = "defaultsfile" Then
                    defaultsFile = Arg
                End If

                ' look for prefixes and store what type for the next iteration.
                NextParm = Nothing
                If Left(Arg, 1) = "/" Then
                    NextParm = Right(Arg, Len(Arg) - 1)
                End If
            Next

            ' Read our parm file and produce a command-line equivalent.
            Dim PracticalArgList As ArrayList

            PracticalArgList = ParseCommandFile(defaultsFile)
            PracticalArgList.AddRange(ParseCommandFile(ArgList(0)))

            ' Iterate over each parm.
            NextParm = Nothing
            For Each Arg In PracticalArgList
                ' See if the value is second part of a tagged one.
                ' The preceding parm has a  '/' prefix).
                If (NextParm = "scrapefrom") Then
                    ScrapeFromSite = ParseBool(Arg)
                End If

                If (NextParm = "dbserver") Then
                    DBServer = Arg
                End If

                If (NextParm = "db") Then
                    DB = Arg
                End If

                If (NextParm = "dblogin") Then
                    DBLogin = Arg
                End If

                If (NextParm = "dbpassword") Then
                    DBPassword = Arg
                End If

                If (NextParm = "sitelogin") Then
                    SiteLogin = Arg
                End If

                If (NextParm = "sitepassword") Then
                    SitePassword = Arg
                End If

                If (NextParm = "docpath") Then
                    FullyQualifiedFilename = Arg
                End If

                NextParm = Nothing

                ' look for prefixes and store what type for the next iteration.
                If Left(Arg, 1) = "/" Then
                    NextParm = Right(Arg, Len(Arg) - 1)
                End If
            Next

            ' Decode the site password.
            Try
                Dim enc As New System.Text.ASCIIEncoding
                Dim pwBytes As Byte() = Convert.FromBase64String(SitePassword)
                SitePassword = enc.GetString(pwBytes)
            Catch ' May fail if not Base 64.  Plain text password is okay so we'll let it fly.
            End Try

            ' Attempt to connect to the database.
            Try
                connStr = String.Format("server={0};user id={1}; password={2}; database={3}; pooling=false", DBServer, DBLogin, DBPassword, DB)

                conn = New MySqlConnection(connStr)
                conn.Open()
                conn.ChangeDatabase(DB)
            Catch ex As Exception
                System.Console.Write("ERROR: Unable to connect to Wiki database")
                Return 8
            End Try

            ' Impersonate as needed.
            If (SiteLogin <> "") Then
                imp = New Impersonator
                If (imp.ImpersonateStart("cdw-1", SiteLogin, SitePassword) = False) Then
                    System.Console.Write("ERROR: Invalid user name or password; please supply valid credentials in order to link this site")
                    Return 8
                End If
            End If

            ' Test site permissions.
            Try
                If (ScrapeFromSite) Then
                    Dim objWC As New System.Net.WebClient
                    Dim cred As ICredentials
                    Dim utf8 As System.Text.UTF8Encoding
                    Dim html As String
                    Dim htmlLower As String
                    Dim URL As String

                    ' Issue the web request.
                    If (Not SiteLogin Is Nothing) Then
                        objWC.Credentials = New Net.NetworkCredential(SiteLogin, SitePassword)
                    End If

                    utf8 = New System.Text.UTF8Encoding
                    html = utf8.GetString(objWC.DownloadData(FullyQualifiedFilename))
                Else
                    System.IO.Directory.GetFiles(FullyQualifiedFilename)
                End If
            Catch
                System.Console.Write("ERROR: Unable to read from the given site; Please check the path name or credentials used to access the site")
                Return 8
            End Try

            Return 0
        Catch ex As Exception
            System.Console.Write(ex.Message)
        Finally
            If (Not conn Is Nothing) Then
                conn.Close()
            End If

            If Not imp Is Nothing Then
                imp.ImpersonateStop()
            End If
        End Try
    End Function

    Function ParseArgs(ByVal ArgList As String(), ByVal NeedToRescanParms As Boolean) As ArrayList
        Dim WorkingParmList As ArrayList
        Dim Arg As String

        WorkingParmList = New ArrayList

        ' Go over each parm.  Reparse them becuase sometimes VB screws them up for some reason.
        For Each Arg In ArgList
            WorkingParmList.AddRange(BreakOutParms(Arg))
        Next

        'If (UBound(ArgList) = 1) Then
        'End If
        ParseArgs = WorkingParmList
    End Function

    Function BreakOutParms(ByVal Text As String) As ArrayList
        Dim WorkingSectionList As ArrayList
        Dim inQuote As Boolean
        Dim WorkingText As String
        Dim ch As Char

        Text = Text + " " ' Make sure we break at end
        WorkingText = ""
        inQuote = False
        WorkingSectionList = New ArrayList

        ' Iterate through and break based on whitespaces, sans quoted things.
        For Each ch In Text
            ' Toggle for quotes.
            If (ch = Chr(34)) Then
                inQuote = Not inQuote
            Else
                ' In a quote - just copy chars over to the result.
                If (inQuote) Then
                    WorkingText = WorkingText + ch
                    ' Break on a whitespace.
                Else
                    If (Char.IsWhiteSpace(ch)) Then
                        WorkingSectionList.Add(Trim(WorkingText))
                        WorkingText = ""
                    Else
                        WorkingText = WorkingText + ch
                    End If

                End If

            End If
        Next

        ' Return our split text.
        BreakOutParms = WorkingSectionList
    End Function

    Function ParseBool(ByVal val As String) As Boolean
        If (val = "") Then
            Return False
        Else
            If val = "true" Or val = "TRUE" Then
                Return True
            Else
                Boolean.Parse(val)
            End If
        End If
    End Function

    Function ParseCommandFile(ByVal CommandFilename As String) As ArrayList
        Dim lineContent As String
        Dim reader As StreamReader
        Dim result As ArrayList = New ArrayList

        ' Read the entire damn file!
        reader = New StreamReader(CommandFilename)

        lineContent = reader.ReadLine
        While (Not lineContent Is Nothing)
            Dim equalPos As Integer
            Dim leftOf As String
            Dim rightOf As String

            equalPos = lineContent.IndexOf("=")
            If (equalPos > 0) Then
                leftOf = lineContent.Substring(0, equalPos)
                rightOf = lineContent.Substring(equalPos + 1)
                result.Add("/" + leftOf.Trim)
                result.Add(rightOf.Trim)
            End If

            lineContent = reader.ReadLine
        End While

        ' Cleanup
        reader.Close()
        ParseCommandFile = result
    End Function
End Module
